#coding=utf-8
from uliweb.core.SimpleFrame import expose
from models import Todo, Comment
from userman.models import UserProfile
from uliweb.orm import get_model
from uliweb import json

User = get_model('user')

def __begin__():
    from uliweb.contrib.auth.views import login
    
    if not request.user:
        return redirect(url_for(login) + '?next=%s' % url_for(doto_index))
    
@expose('/')
def doto_index():
    return {}

def _make_timesince(d):
    from uliweb.utils.timesince import timesince
    if d:
        since, s = timesince(d, flag=True)
        s = s.encode('utf-8')
        if since > 0:
            s = '<font color="red">%s</font>' % s
    else:
        s = ''
    return s
    
def _make_item(todo):
    times = _make_timesince(todo.due_date)
    if todo.finished:
        c = ' class="task-completed"'
    else:
        c = ''
    
    return '''<li id="task_%(id)d"%(completed)s><div class="task-actions">
<a onclick="return deleteTask(%(id)d)" href="#"><img title="delete" onmouseout="this.src=img.del[0]" onmouseover="this.src=img.del[1]" src="%(img)s"></a></div>
<div class="task-duedate">%(timesince)s</div>
<div class="task-left"><input type="checkbox" onclick="completeTask(%(id)d, this)"></div>
        <div class="task-middle"><span>#%(id)d <a href="%(href)s">%(title)s</a></span></div>
</li>''' % {'id':todo.id, 'title':todo.title, 'img':env.url_for_static('images/page_cross_bw.png'),
    'href':url_for('doto.views.doto_show', id=todo.id), 'timesince':times, 'completed':c}

@expose('/add')
def doto_add():
    if request.POST['todo']:
        t = Todo(title=request.POST['todo'], owner=request.user, modify_user=request.user)
        t.save()
        t.users.add(request.user)
        return json({'success':True, 'title':t.title, 'html':_make_item(t)})
    else:
        return json({'success':False, 'message':"The ToDo can't be empty"})
    
@expose('/load')
def doto_load():
    s = []
    filter = request.GET.get('filter')
    query = request.user.todos.filter(Todo.c.deleted==False)
    if filter != 'all':
        query.filter(Todo.c.finished==False)
    for i in query:
        s.append(_make_item(i))
    return ''.join(s)

@expose('/finish/<id>')
def doto_finish(id):
    from uliweb.orm import now
    
    t = Todo.get(int(id))
    t.finished = True
    t.finish_date = now()
    t.save()
    
@expose('/delete/<id>')
def doto_delete(id):
    t = Todo.get(int(id))
#    t.users.clear()
#    t.comments.delete()
    t.deleted = True
    t.save()
    
@expose('/show/<id>')
def doto_show(id):
    from forms import AddUser

    t = Todo.get(int(id))
    
    if not t:
        error("Can't found #%s todo!" % id)
    
    holders = []
    for u in t.users.all():
        holders.append(u.username)
        
    users = User.all()
    choices = [('', '')]
    for u in users:
        if not u.username in holders and u.username != t.owner.username:
            choices.append((u.id, u.username))
        
    AddUser.userid.choices = choices
    f = AddUser()
    
    t.due_date_timesince = _make_timesince(t.due_date)
    
    return {'item':t, 'form':f}

@expose('/save/<id>')
def doto_save(id):
    from uliweb.utils.textconvert import text2html
    
    t = Todo.get(int(id))
    t.modify_user = request.user
    name = request.POST['name']
    result = {'success':True, 'message':'ok'}
    if name == 'task-content':
        t.content = request.POST['content']
        t.save()
        result['content'] = text2html(t.content)
    elif name == 'task-title':
        t.title = request.POST['content']
        t.save()
        result['content'] = t.title
    elif name == 'task-tag':
        tags = request.POST['content'].split()
        t.save_tags(tags)
        t.save()
        result['content'] = ' '.join(t.get_tags())
    elif name == 'task-duedate':
        from uliweb.form import DateTimeField
        
        d = DateTimeField()
        f, dobj = d.validate(request.POST['content'])
        if f:
            t.due_date = dobj
            t.save()
            result['content'] = _make_timesince(dobj)
        else:
            result['message'] = 'Datetime format is not right'
    return json(result)

@expose('/load/<id>')
def doto_get(id):
    t = Todo.get(int(id))
    name = request.POST['name']
    result = {'success':True, 'message':'ok'}
    if name == 'task-content':
        result['content'] = t.content
    elif name == 'task-title':
        result['content'] = t.title
    elif name == 'task-tag':
        result['content'] = ' '.join(t.get_tags())
    return json(result)

def _make_comment(request, c):
    from uliweb.utils.textconvert import text2html
    
    if c.user.username == request.user.username:
        footer = '''<div class="comment-footer">
    <span class="comment-actions">[<a onclick="return deleteComment('%(url)s', %(id)d)" href="#">Delete</a>]</span>
</div>''' % {
    'id':c.id,
    'url':url_for("doto.views.doto_delcomment", id=c.id),
    }
    else:
        footer = ''

    return '''<div class="clearfix comment-line" id="comment_%(id)d">
    <div class="label"><img src="%(image)s" class="user"/></div>
    <div class="comment">
        <div class="comment-header clearfix">
            <span class="comment-user">%(user)s</span>
            <span class="comment-date">%(date)s</span>
        </div>
        <div class="comment-content">%(content)s</div>
        %(footer)s
    </div>
</div>''' % {
    'id':c.id,
    'image':c.user.get_image_url(), 
    'user':c.user.username,
    'date':str(c.date.strftime("%Y-%m-%d %H:%M:%S")),
    'content':text2html(c.content),
    'footer':footer,
    }

@expose('/comment/<id>')
def doto_comment(id):
    t = Todo.get(int(id))
    c = t.comment(content=request.POST['comment'], user=request.user)
    result = {'success':True, 'message':'ok'}
    result['content'] = _make_comment(request, c)
    return json(result)
    
def _make_user(u):
    return '''<li>%(name)s</li>''' % {'name':u.username}

@expose('/getusers/<id>')
def doto_get_users(id):
    t = Todo.get(int(id))

    s = []
    for u in t.users.all():
        if u.username != t.owner.username:
            s.append(_make_user(u))
    return ''.join(s)

@expose('/getcomments/<id>')
def doto_get_comments(id):
    from models import Todo
    t = Todo.get(int(id))
    
    s = []
    for c in t.comments.all():
        s.append(_make_comment(request, c))
        
    return ''.join(s)

    
@expose('/delcomment/<id>')
def doto_delcomment(id):
    c = Comment.get(int(id))
    c.delete()
    
@expose('/adduser/<id>')
def doto_adduser(id):

    userid = request.POST.get('userid', '')
    if userid:
        u = User.get(User.c.id==userid)
        t = Todo.get(int(id))
        
        holders = []
        for x in t.users.all():
            holders.append(x.username)

        if u.username not in holders:
            t.users.add(u)
            content = '<li>%s</li>' % u.username
            result = {'success':True, 'message':'ok', 'content':content}
        else:
            result = {'success':False, 'message':'User %s has been added already.' % u.username}
    else:
        result = {'success':False, 'message':'You should select an username first.'}
        
    return json(result)

